package com.dmall.opening.up.records.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Map;

@Component("http.third.party.order.service")
public class HttpThirdPartyOrderService implements ThirdPartyOrderService {

    @Resource(name = "spring.rest.template.http.client")
    private RestTemplate https;

    @Value("${third.party.order.service.host:http://host}")
    private String host;

    @Override
    public Map<String, Object> cancel(Long id) {
        final ResponseEntity<Map> response = https.postForEntity(
                host + "/orders/" + id,
                Collections.emptyMap(),
                Map.class
        );
        if (response.getStatusCode().is2xxSuccessful()) {
            return response.hasBody() ? response.getBody() : Collections.emptyMap();
        } else {
            throw new RuntimeException();
        }
    }
}
